﻿$(function () {
    document.body.className = localStorage.getItem('config-skin');
    $("[data-toggle='tooltip']").tooltip();
})
$.reload = function () {
    location.reload();
    return false;
}
$.loading = function (bool, text) {
    var $loadingpage = top.$("#loadingPage");
    var $loadingtext = $loadingpage.find('.loading-content');
    if (bool) {
        $loadingpage.show();
    } else {
        if ($loadingtext.attr('istableloading') == undefined) {
            $loadingpage.hide();
        }
    }
    if (!!text) {
        $loadingtext.html(text);
    } else {
        $loadingtext.html("数据加载中，请稍后…");
    }
    $loadingtext.css("left", (top.$('body').width() - $loadingtext.width()) / 2 - 50);
    $loadingtext.css("top", (top.$('body').height() - $loadingtext.height()) / 2);
}
$.request = function (name) {
    var search = location.search.slice(1);
    var arr = search.split("&");
    for (var i = 0; i < arr.length; i++) {
        var ar = arr[i].split("=");
        if (ar[0] == name) {
            if (unescape(ar[1]) == 'undefined') {
                return "";
            } else {
                return unescape(ar[1]);
            }
        }
    }
    return "";
}
$.currentWindow = function () {
    var iframeId = top.$(".ZFine_iframe:visible").attr("id");
    return top.frames[iframeId];
}
$.browser = function () {
    var userAgent = navigator.userAgent;
    var isOpera = userAgent.indexOf("Opera") > -1;
    if (isOpera) {
        return "Opera"
    };
    if (userAgent.indexOf("Firefox") > -1) {
        return "FF";
    }
    if (userAgent.indexOf("Chrome") > -1) {
        if (window.navigator.webkitPersistentStorage.toString().indexOf('DeprecatedStorageQuota') > -1) {
            return "Chrome";
        } else {
            return "360";
        }
    }
    if (userAgent.indexOf("Safari") > -1) {
        return "Safari";
    }
    if (userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera) {
        return "IE";
    };
}
$.download = function (url, data, method) {
    if (url && data) {
        data = typeof data == 'string' ? data : jQuery.param(data);
        var inputs = '';
        $.each(data.split('&'), function () {
            var pair = this.split('=');
            inputs += '<input type="hidden" name="' + pair[0] + '" value="' + pair[1] + '" />';
        });
        $('<form action="' + url + '" method="' + (method || 'post') + '">' + inputs + '</form>').appendTo('body').submit().remove();
    };
};
$.modalOpen = function (options) {
    var defaults = {
        id: null,
        title: '系统窗口',
        width: "100px",
        height: "100px",
        url: '',
        shade: 0.3,
        btn: ['确认', '关闭'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
        callBack: null
    };
    var options = $.extend(defaults, options);
    //修改js 原来宽度没有加300
    var _width = top.$(window).width()+300 > parseInt(options.width.replace('px', '')) ? options.width : top.$(window).width() + 'px';
    var _height = top.$(window).height() > parseInt(options.height.replace('px', '')) ? options.height : top.$(window).height() + 'px';
    top.layer.open({
        id: options.id,
        type: 2,
        shade: options.shade,
        title: options.title,
        fix: false,
        area: [_width, _height],
        content: options.url,
        btn: options.btn,
        btnclass: options.btnclass,
        yes: function () {
            options.callBack(options.id)
        }, cancel: function () {
            return true;
        }
    });
}
$.modalConfirm = function (content, callBack) {
    top.layer.confirm(content, {
        icon: "fa-exclamation-circle",
        title: "系统提示",
        btn: ['确认', '取消'],
        btnclass: ['btn btn-primary', 'btn btn-danger'],
    }, function () {
        callBack(true);
    }, function () {
        callBack(false)
    });
}
$.modalAlert = function (content, type) {
    var icon = "";
    if (type == 'success') {
        icon = "fa-check-circle";
    }
    if (type == 'error') {
        icon = "fa-times-circle";
    }
    if (type == 'warning') {
        icon = "fa-exclamation-circle";
    }
    top.layer.alert(content, {
        icon: icon,
        title: "系统提示",
        btn: ['确认'],
        btnclass: ['btn btn-primary'],
    });
}
$.modalMsg = function (content, type) {
    if (type != undefined) {
        var icon = "";
        if (type == 'success') {
            icon = "fa-check-circle";
        }
        if (type == 'error') {
            icon = "fa-times-circle";
        }
        if (type == 'warning') {
            icon = "fa-exclamation-circle";
        }
        top.layer.msg(content, { icon: icon, time: 4000, shift: 5 });
        top.$(".layui-layer-msg").find('i.' + icon).parents('.layui-layer-msg').addClass('layui-layer-msg-' + type);
    } else {
        top.layer.msg(content);
    }
}
$.modalClose = function () {
    var index = top.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
    var $IsdialogClose = top.$("#layui-layer" + index).find('.layui-layer-btn').find("#IsdialogClose");
    var IsClose = $IsdialogClose.is(":checked");
    if ($IsdialogClose.length == 0) {
        IsClose = true;
    }
    if (IsClose) {
        top.layer.close(index);
    } else {
        location.reload();
    }
}
$.submitForm = function (options) {
    var defaults = {
        url: "",
        param: [],
        loading: "正在提交数据...",
        success: null,
        close: true
    };
    var options = $.extend(defaults, options);
    $.loading(true, options.loading);
    window.setTimeout(function () {
        if ($('[name=__RequestVerificationToken]').length > 0) {
            options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
        }
        $.ajax({
            url: options.url,
            data: options.param,
            type: "post",
            dataType: "json",
            success: function (data) {
                if (data.state == "success") {
                    options.success(data);
                    $.modalMsg(data.message, data.state);
                    if (options.close == true) {
                        $.modalClose();
                    }
                } else {
                   
                    $.modalAlert(data.message, data.state);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.loading(false);
                $.modalMsg(errorThrown, "error");
            },
            beforeSend: function () {
                $.loading(true, options.loading);
            },
            complete: function () {
                $.loading(false);
            }
        });
    }, 500);
}

//新加的方法 提交数据 返回失败时也会关闭窗口
$.submitFormAndCloseWin = function (options) {
    var defaults = {
        url: "",
        param: [],
        loading: "正在提交数据...",
        success: null,
        close: true
    };
    var options = $.extend(defaults, options);
    $.loading(true, options.loading);
    window.setTimeout(function () {
        if ($('[name=__RequestVerificationToken]').length > 0) {
            options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
        }
        $.ajax({
            url: options.url,
            data: options.param,
            type: "post",
            dataType: "json",
            success: function (data) {
                if (data.state == "success") {
                    options.success(data);
                    $.modalMsg(data.message, data.state);
                    if (options.close == true) {
                        $.modalClose();
                    }
                } else {

                    $.modalAlert(data.message, data.state);
                    //新加在返回来的数据是失败的情况下也关闭窗口
                    $.modalClose();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $.loading(false);
                $.modalMsg(errorThrown, "error");
            },
            beforeSend: function () {
                $.loading(true, options.loading);
            },
            complete: function () {
                $.loading(false);
            }
        });
    }, 500);
}

$.deleteForm = function (options) {
    var defaults = {
        prompt: "注：您确定要删除该项数据吗？",
        url: "",
        param: [],
        loading: "正在删除数据...",
        success: null,
        close: true
    };
    var options = $.extend(defaults, options);
    if ($('[name=__RequestVerificationToken]').length > 0) {
        options.param["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }
    $.modalConfirm(options.prompt, function (r) {
        if (r) {
            $.loading(true, options.loading);
            window.setTimeout(function () {
                $.ajax({
                    url: options.url,
                    data: options.param,
                    type: "post",
                    dataType: "json",
                    success: function (data) {
                        if (data.state == "success") {
                            options.success(data);
                            $.modalMsg(data.message, data.state);
                        } else {
                            $.modalAlert(data.message, data.state);
                        }
                    },
                    error: function (XMLHttpRequest, textStatus, errorThrown) {
                        $.loading(false);
                        $.modalMsg(errorThrown, "error");
                    },
                    beforeSend: function () {
                        $.loading(true, options.loading);
                    },
                    complete: function () {
                        $.loading(false);
                    }
                });
            }, 500);
        }
    });

}
$.jsonWhere = function (data, action) {
    if (action == null) return;
    var reval = new Array();
    $(data).each(function (i, v) {
        if (action(v)) {
            reval.push(v);
        }
    })
    return reval;
}
$.fn.jqGridRowValue = function () {
    var $grid = $(this);
    var selectedRowIds = $grid.jqGrid("getGridParam", "selarrrow");
    if (selectedRowIds != "") {
        var json = [];
        var len = selectedRowIds.length;
        for (var i = 0; i < len ; i++) {
            var rowData = $grid.jqGrid('getRowData', selectedRowIds[i]);
            json.push(rowData);
        }
        return json;
    } else {
        return $grid.jqGrid('getRowData', $grid.jqGrid('getGridParam', 'selrow'));
    }
}
$.fn.formValid = function () {
    return $(this).valid({
        errorPlacement: function (error, element) {
            element.parents('.formValue').addClass('has-error');
            element.parents('.has-error').find('i.error').remove();
            element.parents('.has-error').append('<i class="form-control-feedback fa fa-exclamation-circle error" data-placement="left" data-toggle="tooltip" title="' + error + '"></i>');
            $("[data-toggle='tooltip']").tooltip();
            if (element.parents('.input-group').hasClass('input-group')) {
                element.parents('.has-error').find('i.error').css('right', '33px')
            }
        },
        success: function (element) {
            element.parents('.has-error').find('i.error').remove();
            element.parent().removeClass('has-error');
        }
    });
}
$.fn.formSerialize = function (formdate) {
    var element = $(this);

    ///上传文件类型以及尺寸提醒
    var fileAlert = function (FileAlertID) {
        ///格式 上传控件类型+类别ID+序列
        switch (FileAlertID) {
            //case "imagefile+1": return { "IsMin": "Allow", "MinWidth": "480", "MinHeight": "228", "FileType": "Image", "maxsize": 20480, "max": 2048, "text": "" }; break;//添加图片
              case "imagefile+1": return { "IsMin": "Allow", "MinWidth": "480", "MinHeight": "228", "FileType": "Image", "maxsize": 2048, "max": 1, "text": " " }; break;//logo图
            case "imagefile+12+1": return { "IsMin": "Allow", "MinWidth": "480", "MinHeight": "228", "FileType": "Image", "maxsize": 2048, "max": 1, "text": "上传的图片尺寸最佳为480px*228px;格式为jpg,png,gif" }; break;//logo图
            case "imagefile+13+1": return { "IsMin": "Allow", "MinWidth": "480", "MinHeight": "228", "FileType": "Image", "maxsize": 2048, "max": 1, "text": "上传的图片尺寸最佳为480px*228px;格式为jpg,png,gif" }; break;//logo图
            case "imagefile+28+1": return { "IsMin": "Allow", "MinWidth": "480", "MinHeight": "186", "FileType": "Image", "maxsize": 2048, "max": 1, "text": "上传的图片尺寸最佳为480px*186px;格式为jpg,png,gif" }; break;//logo图
            case "imagefile+32+1": return { "IsMin": "Allow", "MinWidth": "640", "MinHeight": "458", "FileType": "Image", "maxsize": 2048, "max": 1, "text": "上传的图片尺寸最佳为480px*340px;格式为jpg,png,gif" }; break;//logo图
            case "imagefile+33+1": return { "IsMin": "Allow", "MinWidth": "640", "MinHeight": "503", "FileType": "Image", "maxsize": 2048, "max": 1, "text": "上传的图片尺寸最佳为480px*250px;格式为jpg,png,gif" }; break;//logo图


            case "imagefile+MerchantBanner+1": return { "IsMin": "Allow", "MinWidth": "480", "MinHeight": "228", "FileType": "Image", "maxsize": 2048, "max": 1, "text": "上传的图片尺寸最佳为480px*228px;格式为jpg,png,gif" }; break;//logo图

            case "imagefile+MemberLevel+1": return { "IsMin": "Allow", "MinWidth": "300", "MinHeight": "300", "FileType": "Image", "maxsize": 2048, "max": 1, "text": "上传的图片尺寸最佳为300px*150px;格式为jpg,png,gif" }; break;
                ///基础数据维护
            case "imagefile+Product+1": return { "IsMin": "Allow", "MinWidth": "300", "MinHeight": "300", "FileType": "Image", "maxsize": 2048, "max": 1, "text": "上传的图片尺寸最佳为：600px*600px;格式为jpg,png,gif" }; break;
            case "imagefile+Product+2": return { "IsMin": "Allow", "MinWidth": "300", "MinHeight": "300", "FileType": "Image", "maxsize": 2048, "max": 6, "text": "上传的图片尺寸最佳为：600px*600px;最多可上传6张图片,格式为jpg,png,gif" }; break;
            case "imagefile+BrandID+1": return { "IsMin": "Allow", "MinWidth": "300", "MinHeight": "300", "FileType": "Image", "maxsize": 2048, "max": 1, "text": "上传的图片尺寸最佳为100px*100px;格式为jpg,png,gif" }; break;
            case "imagefile+ProductCategoryID+1": return { "IsMin": "Allow", "MinWidth": "300", "MinHeight": "300", "FileType": "Image", "maxsize": 2048, "max": 1, "text": "上传的图片尺寸最佳为100px*100px;格式为jpg,png,gif" }; break;
            case "imagefile+Merchant+1": return { "IsMin": "Allow", "MinWidth": "300", "MinHeight": "300", "FileType": "Image", "maxsize": 2048, "max": 1, "text": "上传的图片尺寸最佳为400px*400px;格式为jpg,png,gif" }; break;//logo图
                ///一下信息请勿删除
            case "imagefile+logo+1": return { "FileType": "Image", "maxsize": 2048, "max": 1, "text": "请根据页面上传最佳比例;格式为jpg,png,gif" }; break;//logo图
            case "imagefile+IsWatermark+1": return { "IsWatermark": "IsWatermark", "IsMax": "Allow", "MaxWidth": "600", "MaxHeight": "600", "IsMin": "Allow", "MinWidth": "200", "MinHeight": "200", "FileType": "Image", "maxsize": 2048, "max": 1, "text": "上传的图片尺寸最佳为600px*600px;格式为jpg,png,gif" }; break;//水印图属性
            case "imagefile+Watermark+1": return { "FileType": "Image", "maxsize": 2048, "max": 1, "text": "上传水印图片为原图上传;格式为jpg,png,gif" }; break;//水印图
            case "file+1": return { "FileType": "File", "maxsize": 20480, "max": 1, "text": "建议上传.rar .zip文件" }; break;//文件类型
            case "file+3": return { "FileType": "Video", "maxsize": 20480, "max": 1, "text": "上传视频文件;格式为flv,avi,mp4,mov,3gp" }; break;//视频类型
            case "file+4": return { "FileType": "File", "maxsize": 20480, "max": 1, "text": "建议上传.rar .zip office文件" }; break;//文件类型
            default: return { "IsMax": "Allow", "MaxWidth": "600", "MaxHeight": "600", "IsMin": "Allow", "MinWidth": "200", "MinHeight": "200", "FileType": "Image", "maxsize": 2048, "max": 2048, "text": "" }; break;
        }
    };
    //上传图片控件
    var creatImageFile = function ($this) {
        debugger;
        ///生命一个时间戳 来当做upload的id 这样可以防止重复
        var k = fileAlert("imagefile+" + $this.attr("index"));
        var UploadID = (Math.random() + "").replace("0.", "ImageFile");
        $this.parent().prepend('<div class="grid"><input class="g-u"  id=' + UploadID + ' name="Filedata" type="file"  value="' + $this.attr("text") + '"> <input type="hidden" editor="imagefile"  id ="J_Urls' + UploadID + '" field=' + $this.attr("field") + ' name="imageUrls"> <ul id ="J_UploaderQueue' + UploadID + '" class="grid J_UploaderQueue"></ul></div><div style="float: left; height: 35px; line-height:35px; "><span class="xing ww">' + k.text + '</span></div>');
        var S = KISSY;
        var srcPath = RootPath + "/";
        S.config({
            packages: [
                {
                    name: "gallery",
                    path: srcPath
                }
            ]
        });
        S.use('gallery/uploader/1.4/index,gallery/uploader/1.4/themes/imageUploader/index,gallery/uploader/1.4/themes/imageUploader/style.css', function (S, Uploader, ImageUploader) {
            //上传组件插件
            var plugins = 'gallery/uploader/1.4/plugins/auth/auth,' +
                    'gallery/uploader/1.4/plugins/urlsInput/urlsInput,' +
                    'gallery/uploader/1.4/plugins/proBars/proBars,' +
                    'gallery/uploader/1.4/plugins/filedrop/filedrop,' +
                    'gallery/uploader/1.4/plugins/preview/preview,' +
                    'gallery/uploader/1.4/plugins/tagConfig/tagConfig';
            S.use(plugins, function (S, Auth, UrlsInput, ProBars, Filedrop, Preview, TagConfig) {
                var uploader = new Uploader('#' + UploadID, {
                    action: RootPath + "/Project/Uploadify/Upload",
                    multiple: true,
                    data: k
                });
                //触发事件
                var queue = uploader.get('queue');
                $("#J_Urls" + UploadID).bind("SetImageFiles", function (FileNames) {
                    uploader.restore();
                });
                //使用主题
                uploader.theme(new ImageUploader({
                    queueTarget: '#J_UploaderQueue' + UploadID
                }));
                uploader.on('remove', function (a) {
                    $.post(RootPath + "/Project/Uploadify/DeleteImage", { FilePath: a.file.result.url });
                });
                //验证插件
                uploader.plug(new Auth({
                    //最多上传个数
                    max: k.max,
                    //图片最大允许大小
                    maxSize: k.maxsize,
                    allowExts: k.allowexts
                }))
                //url保存插件
                .plug(new UrlsInput({ target: '#J_Urls' + UploadID }))
                //进度条集合
                .plug(new ProBars())
                //拖拽上传
                .plug(new Filedrop())
                //图片预览
                .plug(new Preview())
                .plug(new TagConfig());
                //渲染默认数据
                uploader.restore();
            });
        });
        $this.remove();
    };
    //上传文件控件
    var creatFile = function ($this) {
        //var k = FileAlert("file+" + queryParams["FileAlertID"] + "+" + $this.attr("index"));
        var k = fileAlert("file+" + $this.attr("index"));
        ///生命一个时间戳 来当做upload的id 这样可以防止重复
        var UploadID = (Math.random() + "").replace("0.", "File");
        $this.parent().prepend('<div class="grid"> <input class="g-u"  id=' + UploadID + ' name="Filedata" type="file"  value="' + $this.attr("text") + '"> <input type="hidden" editor="file"  id ="J_Urls' + UploadID + '" field=' + $this.attr("field") + ' name="imageUrls"> <ul id ="J_UploaderQueue' + UploadID + '" class="grid J_UploaderQueue"></ul></div><div style="float: left; height: 35px; line-height:35px; "><span class="xing ww">' + k.text + '</span></div>');
        var S = KISSY;
        var srcPath = RootPath + "/";
        S.config({
            packages: [
                {
                    name: "gallery",
                    path: srcPath
                }
            ]
        });
        S.use('gallery/uploader/1.4/index,gallery/uploader/1.4/themes/default/index,gallery/uploader/1.4/themes/default/style.css', function (S, Uploader, DefaultTheme) {
            //上传组件插件
            var plugins = 'gallery/uploader/1.4/plugins/auth/auth,' +
                    'gallery/uploader/1.4/plugins/urlsInput/urlsInput,' +
                    'gallery/uploader/1.4/plugins/proBars/proBars';

            S.use(plugins, function (S, Auth, UrlsInput, ProBars, Filedrop, Preview, TagConfig) {
                var uploader = new Uploader('#' + UploadID, {
                    action: RootPath + "/Project/Uploadify/Upload",
                    // multiple: true,
                    data: k

                });
                //使用主题
                uploader.theme(new DefaultTheme({
                    queueTarget: '#J_UploaderQueue' + UploadID
                }))
                uploader.on('remove', function (a) {
                    $.post(RootPath + "/Uploadify/DeleteImage", { FilePath: a.file.result.url });
                });
                //验证插件
                uploader.plug(new Auth({
                    //最多上传个数
                    max: k.max,
                    //图片最大允许大小
                    //  maxSize: k.maxsize,
                    allowExts: k.allowexts
                }))
                    //url保存插件
                .plug(new UrlsInput({ target: '#J_Urls' + UploadID }))
                //进度条集合
                .plug(new ProBars());
                //渲染默认数据
                uploader.restore();

            });
        });
        $this.remove();
    };
    ///创建百度编辑器实例
    var creatUeditor = function ($this) {
        var TimeStamp = "ueditor" + Math.random();
        var TextUEditor = $('<textarea id="' + TimeStamp + '" field=' + $this.attr("field") + ' editor="ueditor" style="width:100%; height:400px;"></textarea>');
        TextUEditor.appendTo($this.parent());
        var editor = UE.getEditor(TimeStamp);
        $this.remove();
        return editor;
    };
    //创建下拉
    var creatCombotree = function ($this) {
        var onlyLeaf = "true";
        var multiple = false;
        if ($this.attr("onlyleaf") != undefined)
            onlyLeaf = $this.attr("onlyleaf");
        if ($this.attr("multiple") != undefined)
            multiple = $this.attr("multiple");
        //source表示要渲染成combotree的对象 
        //params表示请求的地址
        //width是combotree的宽度设置，
        //onlyLeaf表示是否只允许单击子节点true，表示只允许单击子节点
        //UrlParams:通过Url地址栏传递的参数
        var option = { "source": $this, "params": $this.attr("url"), "onlyLeaf": onlyLeaf, "UrlParams": "", multiple: Boolean(multiple) };
        //source, params, width, onlyLeaf
        if (option.wdith == null) option.wdith = 345;
        if (option.multiple == undefined) option.multiple = false;
        option.source.combotree({
            url: option.params + option.UrlParams,
            width: option.width,
            valueField: 'id',
            textField: 'text',
            onlyLeafCheck: true,
            animate: true,
            editable: false,
            multiple: option.multiple,
            onBeforeSelect: function (node) {
                if (option.onlyLeaf == "true") {
                    var t = $(this).tree;
                    var isLeaf = t('isLeaf', node.target);
                    if (!isLeaf) {
                        return false;
                    }
                } else {
                    return true;
                }
            }
        });
    };

    var creatUploadify = function ($this) {
        var TimeStampShow = ("Uploadify" + Math.random()).replace("0.", "");
        var AllHtml = $('<span id=' + TimeStampShow + '></span><div class="helptitle">建议尺寸为640像素x640像素，大小不超过500kb 默认显示第1张图片，最多20张 (可拖拽图片调整显示顺序 )</div><div id="some_file_queue' + TimeStampShow + '"></div><div><ul id="ImageItem" class="ImageItems"><input type="hidden" editor="uploadifyfile" field=' + $this.attr("field") + ' /></ul></div>');
        $this.parent().append(AllHtml);
        var All = $this.parent();
        var ImageListItem = All.find("#ImageItem");
        var uploadifyobject = All.find("#" + TimeStampShow + "");
        //计算隐藏域的值
        var compute_input = function (ImageItem) {
            var Input = ImageItem.find('[type="hidden"]');
            var ImageList = ImageItem.find('[data-url]');
            Input.val(ImageList.map(function () {
                return $(this).attr("data-url");
            }).get().join(","));
        };
        //生成上传控件
        uploadifyobject.uploadify({
            queueID: "some_file_queue" + TimeStampShow,
            buttonClass: 'addbtn',
            swf: RootPath + "/Content/Uploadify/uploadify.swf",  // The path to the uploadify SWF file
            uploader: RootPath + "/Uploadify/Upload",  // The path to the server-side upload script
            onUploadSuccess: function (file, data, response) {
                var json = eval('(' + data + ')');
                var ImageLi = $('<li class="drag-item" ><span class="item_box"><img src=' + RootPath + json.url + ' data-url=' + json.url + ' /></span></li>');
                $('<a class="item_new_close item_close"></a>').bind("click", function () {
                    $.post(RootPath + "/Uploadify/DeleteImage", { FilePath: $(this).closest("li").find("img").attr("data-url") });
                    var $this_li = $(this);
                    $this_li.parent("li").hide(500, function () {
                        $this_li.parent("li").remove();
                        compute_input(ImageListItem);
                    });
                }).appendTo(ImageLi);
                ImageListItem.append(ImageLi);
                compute_input(ImageListItem);
                All.find("#ImageItem").sortable({
                    opacity: 0.7,
                    stop: function () {
                        compute_input(ImageListItem);
                    }
                });
                All.find("#ImageItem").disableSelection();
            }
        });
        $this.remove();
    }



    //遍历找出带有editor的元素并且进行渲染
    element.find("editor").each(function (index, element) {
        var $this = $(this);
        debugger;
        switch ($this.attr("editor")) {
            case "ueditor": creatUeditor($this); break;
            case "imagefile": creatImageFile($this); break;
            case "file": creatFile($this); break;
            case "combotree": creatCombotree($this); break;
            case "uploadifyfile": creatUploadify($this); break;
        }
    });
    //debugger;
    if (!!formdate) {
        for (var key in formdate) {
            var $id = element.find('#' + key);
            var value = $.trim(formdate[key]).replace(/&nbsp;/g, '');
            var type = $id.attr('type');
            if ($id.hasClass("select2-hidden-accessible")) {
                type = "select";
            }
            switch (type) {
                case "checkbox":
                    if (value == "true") {
                        $id.attr("checked", 'checked');
                    } else {
                        $id.removeAttr("checked");
                    }
                    break;
                case "select":
                    $id.val(value).trigger("change");
                    break;
                default:
                    $id.val(value);
                    break;
            }
        };
        element.bindData(formdate, { field: 'field' });
        return false;
    } else if (formdate!=undefined&&formdate =='') {
        return false;
    }

    debugger;
    var postdata = {};
    element.find('input,select,textarea').each(function (r) {
        var $this = $(this);
        var id = $this.attr('id');
        var type = $this.attr('type');
        switch (type) {
            case "checkbox":
                postdata[id] = $this.is(":checked");
                break;
            default:
                var value = $this.val() == "" ? "&nbsp;" : $this.val();
                if (!$.request("keyValue")) {
                    value = value.replace(/&nbsp;/g, '');
                }
                postdata[id] = value;
                break;

        }
    });
    var InputList = element.find("[field]");
    postdata = InputList.loadData({ name: "field", data: postdata });
    postdata = $.fn.getEasyRows({ data: postdata });




    if ($('[name=__RequestVerificationToken]').length > 0) {
        postdata["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();
    }
    return postdata;
};

//提取数据，服务器参数格式
jQuery.fn.loadData = function (option) {
    if (option.data == undefined) {
        data = {};
    } else {
        data = option.data;
    }
    if (option.name == undefined) {
        option["name"] = "id";
    }
    var names = [];
    jQuery(this).each(function () {
        var input = jQuery(this);
        var id = input.attr(option.name);
        if (id == undefined) {
            return true;
        }
        var idx = id;
        if (option.prefix != undefined) {
            idx = option.prefix + "." + id
        }
        var value = "";
        var editor = input.attr("editor");
       
        switch (editor) {
            case 'ueditor':
                debugger;
                var ue = UE.getEditor(input.attr("id"));
                data[idx] = ue.getContent();
                //if (ue.hasContents().length>0) {
                //    data[idx] = ue.getContent();
                //}
                break;
            case 'combotree':
                if (input.attr("multiple") == "multiple") {
                    //data[idx] = input.combobox("getText");
                    data[idx] = input.combobox("getValues");
                }
                else {
                    if (input.attr("getvalue") != undefined)
                        data[idx] = input.combobox(input.attr("getvalue"));
                    else
                        data[idx] = input.combobox("getValue");

                }
                break;
            case 'datetimebox': data[idx] = input.datetimebox('getValue'); break;
            case 'datebox': data[idx] = input.datebox('getValue'); break;
            default:
                debugger;
                if (input.is(":radio")) {
                    if (input.prop("checked")) {

                    } else {
                        return true;
                    }
                }
                if (input.is(":checkbox")) {
                    if (input.attr("checked")) {
                    } else {
                        data[idx] = false;
                        return true;
                    }
                }
                //特殊处理：处理后台图片上传为null不保存
                if (input.context.name == 'imageUrls') {
                    var getvaluetemp = input.attr("getvalue");
                    if (getvaluetemp == '' || getvaluetemp == undefined) {
                        if (input.attr("getvalue") == undefined) {
                            try {
                                var getvaluetemp = "val()";
                                var returnvalues = value = eval("input." + getvaluetemp);
                                returnvalues = eval("input." + getvaluetemp);
                                if (returnvalues == '') {
                                    data[idx] = '"&nbsp;';
                                    return true;
                                } 
                            } catch (e) {
                                return true;
                            } 
                        }
                        //data[idx] = '"&nbsp;';
                        //return true;
                    }
                }


                var getvalue = input.attr("getvalue");

                try {
                    if (getvalue == undefined) {
                        getvalue = "val()";
                    }

                    value = eval("input." + getvalue);
                } catch (e) {
                    return true;
                }
                debugger;
                if (value == "") {
                    names.push(id);
                }
                data[idx] = value;
                break;
        }

    });
    if (option.required) {
        for (var i = 0; i < names.length; i++) {
            data["required[" + i + "]"] = names[i];
        }
    }
    return data;
}


//对象转参数
jQuery.fn.getEasyRows = function (option) {
    var opt = {
        prefix: '',
        data: {}
        //key:undefined
    };
    if (option != undefined) {
        jQuery.extend(true, opt, option);
    }
    var prefix = opt.prefix;
    var key = opt.key;
    var data = opt.data;
    var ret = {};
    switch (jQuery.type(data)) {
    case 'array':
        for (var i = 0; i < data.length; i++) {
            jQuery.extend(true, ret, jQuery.fn.getEasyRows({ data: data[i], prefix: prefix + '[' + i + ']', key: key }));
        }
        break;
    case 'object':
        if (key == undefined) {
            for (var id in data) {
                jQuery.extend(true, ret, jQuery.fn.getEasyRows({ data: data[id], prefix: (prefix == '' ? '' : prefix + '.') + id }));
            }
        } else if (data[key] != undefined) {
            ret[prefix] = data[key];
        }
        break;
    case 'boolean':
        if (prefix != '') {
            ret[prefix] = data + '';
        }
        break;
    case "string":
        if (data.indexOf("/Date(") == 0) {
            if (jQuery.type(eval(data))) {
                if (prefix != '') {
                    ret[prefix] = eval('new ' + eval(data).source).format('yyyy-MM-dd hh:mm:ss');;
                }
                break;
            }
        }
        if (prefix != '') {
            ret[prefix] = data;
        }
        break;
    default:
        if (prefix != '') {
            ret[prefix] = data;
        }
        break;
    }
    return ret;
};

jQuery.fn.bindData = function (data, option) {
    if (option == undefined) {
        option = {};
    }
    if (option.field == undefined) {
        option["field"] = "field";
    }
    jQuery(this).each(function () {
        var fields;
        if (jQuery(this).attr(option.field) != null) {
            fields = jQuery(this).add(jQuery(this).find("[" + option.field + "]"));
        } else {
            fields = jQuery(this).find("[" + option.field + "]");
        }
        for (var i = fields.length - 1; i >= 0; i--) {
            var input = jQuery(fields[i]);
            var field = input.attr(option.field);
            var value = "";
            var column = {};
            if (field != undefined) {
                column["field"] = field;
            }
            column["target"] = this;
            try {
                value = eval("data." + field);
            } catch (e) {
            }
            try {
                var formatter = input.attr("formatter");
                if (formatter != undefined) {
                    column.formatter = eval(formatter);
                    value = column.formatter(value, data, 0);

                }
                if (input.attr("editor")) {
                    switch (input.attr("editor")) {
                        case "ueditor": SetContent(input, value, data); break;
                        case "imagefile": SetImageFile(input, value, data); break;
                        case "file": SetImageFile(input, value, data); break;
                        case "datetimebox": input.val(ChangeDateFormat(value)); break;
                        case 'datebox': input.datebox("setValue", value); break;
                        case "combotree": input.combotree('setValue', value); break;
                        case "uploadifyfile": SetUploadify(input, value, data); break;
                    }
                }
                else {
                    switch (true) {
                        case input.is("select"):
                            var opt = input.find("option[value='" + value + "']");
                            if (opt.length == 0) {
                                input.append("<option value='" + value + "' selected>" + value + "</option>");
                            } else {
                                opt.attr("selected", true);
                            }; break;
                        case input.is(":radio"):
                        case input.is(":checkbox"):
                            if (input.val() == value + "") {
                                input.prop('checked', true);
                            } else {
                                input.prop('checked', false);
                            };
                            break;
                        case input.is("textarea"): input.val(value); break;
                        case input.is("input"): input.val(value); break;
                        default: input.html(value); break;
                    }
                }

            } catch (e) {
                alert(e.message);
                input.html(value);
            }
        }
    });
}


function ChangeDateFormat(time) {
    if (time != null) {
        var date = new Date(parseInt(time.replace("/Date(", "").replace(")/", ""), 10));
        var month = date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
        var currentDate = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
        var Hours = date.getHours();
        var Minutes = date.getMinutes();
        var Seconds = date.getSeconds();
        return date.getFullYear() + "-" + month + "-" + currentDate + " " + Hours + ":" + Minutes;
    }
    return "";
}

var SetUploadify = function (input, value, data) {
    if (value) {
        input.val(value);
        var ArrayImages = value.split(',');
        var ImageListItem = $(input).parent();
        //计算隐藏域的值
        var compute_input = function (ImageItem) {
            var Input = ImageItem.find('[type="hidden"]');
            var ImageList = ImageItem.find('[data-url]');
            Input.val(ImageList.map(function () {
                return $(this).attr("data-url");
            }).get().join(","));
        };
        $.each(ArrayImages, function (Index, Element) {
            var ImageLi = $('<li class="drag-item" ><span class="item_box"><img src=' + RootPath + Element + ' data-url=' + Element + ' /></span></li>');
            $('<a class="item_new_close item_close"></a>').bind("click", function () {
                $.post(RootPath + "/Uploadify/DeleteImage", { FilePath: $(this).closest("li").find("img").attr("data-url") });
                var $this_li = $(this);
                $this_li.parent("li").hide(500, function () {
                    $this_li.parent("li").remove();
                    compute_input(ImageListItem);
                });
            }).appendTo(ImageLi);
            ImageListItem.append(ImageLi);
            ImageListItem.sortable({
                opacity: 0.7,
                stop: function () {
                    compute_input(ImageListItem);
                }
            });
            ImageListItem.disableSelection();
        });
    }

}


///设置编辑器的内容
var SetContent = function (input, value, data) {
    if (value) {
        debugger;
        var ue = UE.getEditor(input.attr("id"));
        ue.ready(function () {
            ue.setContent(value);
        })
    }
}
//设置图片上传的内容
var SetImageFile = function (input, value, data) {
    if (value) {
        value = value.split(',');
        var jsonList = '<script type="text/uploader-files"> [';
        for (var i = 0; i < value.length; i++) {
            if (i == 0) {
                jsonList += '{ "name":"' + value[i] + '","url": "' + value[i] + '" }';
            }
            else {
                jsonList += ',{  "name":"' + value[i] + '","url": "' + value[i] + '" }';
            }

        }
        jsonList += ']<\/script>';
        ///万恶的JsonList
        input.next("ul").append(jsonList);
        $(input).trigger("SetImageFiles");//触发 
    }
}


$.fn.bindSelect = function (options) {
    var defaults = {
        id: "id",
        text: "text",
        search: false,
        url: "",
        param: [],
        change: null
    };
    var options = $.extend(defaults, options);
    var $element = $(this);
    if (options.url != "") {
        $.ajax({
            url: options.url,
            data: options.param,
            dataType: "json",
            async: false,
            success: function (data) {
                $.each(data, function (i) {
                    $element.append($("<option></option>").val(data[i][options.id]).html(data[i][options.text]));
                });
                $element.select2({
                    minimumResultsForSearch: options.search == true ? 0 : -1
                });
                $element.on("change", function (e) {
                    if (options.change != null) {
                        options.change(data[$(this).find("option:selected").index()]);
                    }
                    $("#select2-" + $element.attr('id') + "-container").html($(this).find("option:selected").text().replace(/　　/g, ''));
                });
            }
        });
    } else {
        $element.select2({
            minimumResultsForSearch: -1
        });
    }
}
$.fn.authorizeButton = function () {
    var moduleId = top.$(".ZFine_iframe:visible").attr("id").substr(6);
    var dataJson = top.clients.authorizeButton[moduleId];
    var $element = $(this);
    $element.find('a[authorize=yes]').attr('authorize', 'no');
    if (dataJson != undefined) {
        $.each(dataJson, function (i) {
            $element.find("#" + dataJson[i].F_EnCode).attr('authorize', 'yes');
        });
    }
    $element.find("[authorize=no]").parents('li').prev('.split').remove();
    $element.find("[authorize=no]").parents('li').remove();
    $element.find('[authorize=no]').remove();
}
$.fn.dataGrid = function (options) {
    var defaults = {
        datatype: "json",
        autowidth: true,
        rownumbers: true,
        shrinkToFit: false,
        gridview: true
    };
    var options = $.extend(defaults, options);
    var $element = $(this);
    options["onSelectRow"] = function (rowid) {
        var length = $(this).jqGrid("getGridParam", "selrow").length;
        var $operate = $(".operate");
        if (length > 0) {
            $operate.animate({ "left": 0 }, 200);
        } else {
            $operate.animate({ "left": '-100.1%' }, 200);
        }
        $operate.find('.close').click(function () {
            $operate.animate({ "left": '-100.1%' }, 200);
        })
    };
    $element.jqGrid(options);
};